package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 后台派送 修改派送状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> delivery(@RequestBody Orders orders) {
        log.info("派送订单 id：{}", orders);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Orders::getId, orders.getId());

        Orders one = orderService.getOne(queryWrapper);

        if (one != null) {
            one.setStatus(orders.getStatus());
            orderService.updateById(one);
            return R.success("成功");
        }

        return R.error("失败");
    }

    /**
     * 订单信息分页查询
     *
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @param number
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize, String number, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beginTime, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        log.info("page = {},pageSize = {}", page, pageSize);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);


        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加条件

        queryWrapper.eq(number != null, Orders::getId, number);

        queryWrapper.ge(beginTime != null, Orders::getOrderTime, beginTime);
        queryWrapper.le(endTime != null, Orders::getOrderTime, endTime);


        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        orderService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);

    }

    /**
     * 用户端订单信息分页查询
     *
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @return
     */
    @GetMapping("/userPage")
    public R page(int page, int pageSize) {

        //获得当前用户id
        Long userId = BaseContext.getCurrentId();

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        Page orderDtoInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(Orders::getUserId, userId);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行查询
        orderService.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, orderDtoInfo, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((order) -> {

            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order, ordersDto);

            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> list1 = orderDetailService.list(lambdaQueryWrapper);

            ordersDto.setOrderDetails(list1);

            return ordersDto;
        }).collect(Collectors.toList());

        orderDtoInfo.setRecords(list);

        return R.success(orderDtoInfo);

    }

    /**
     * 再来一单
     *
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R again(@RequestBody Orders orders) {

        log.info("再来一单：{}");

        Long currentId = BaseContext.getCurrentId();

        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
        List<OrderDetail> list1 = orderDetailService.list(lambdaQueryWrapper);

        for (int i = 0; i <list1.size() ; i++) {
            OrderDetail orderDetail = list1.get(i);

            LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShoppingCart::getDishId,orderDetail.getDishId());
            queryWrapper.eq(ShoppingCart::getUserId,currentId);
            ShoppingCart one = shoppingCartService.getOne(queryWrapper);

            if (one == null) {
                ShoppingCart shoppingCart = new ShoppingCart();

                BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
                shoppingCart.setUserId(currentId);

                shoppingCartService.save(shoppingCart);
            }else {
                Integer number = one.getNumber();
                number = number +1;
                one.setNumber(number);
                shoppingCartService.updateById(one);
            }



        }

        return R.success("再来一单");

    }

}